package cn.tanghom.app.oa.service;

import java.util.Date;

import lombok.val;

import org.flowable.engine.delegate.BpmnError;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tanghom.app.oa.model.Candidate;
import cn.tanghom.app.oa.repository.CandidateRepository;
import cn.tanghom.app.oa.repository.TalentRepository;

/**
 * 创建面试记录 
 * @author Hunteron-cp
 *
 */
@Service
public class InterviewProcessDelegate implements JavaDelegate {
	
  @Autowired
  private TalentRepository talentRepository;
  
  @Autowired
  private CandidateRepository candidateRepository;

  @Override
  public void execute(DelegateExecution execution) {
    Date now = new Date();
    Boolean matched = (Boolean)execution.getVariable("matched");
    if(matched){
	    Object talentId = execution.getVariable("talentId");
	    if(talentId==null){
	    	execution.setTransientVariable("errorMessage", "not existed!");
	    	throw new BpmnError("BusinessExceptionOccurred");
	    	//return ;
	    }
	    Long positionId = (Long) execution.getVariable("positionId");
	    if(positionId==null){
	    	execution.setTransientVariable("errorMessage", "not existed!");    	
	    	throw new BpmnError("BusinessExceptionOccurred");
	    	//return ;
	    }
	    
	    
	    long candidateCount = candidateRepository.countByPositionId(positionId);
	    Candidate cand = new Candidate();
	    cand.setPositionId(positionId);
	    cand.setTalentId(Long.parseLong(talentId.toString()));
	    cand.setCreateTime(now);
	    cand.setMatchScore(1.0f);
	    
	    candidateRepository.save(cand);
	    
	    execution.setTransientVariable("candidate", cand);	    
	    execution.setVariable("candidateCount",candidateCount);
	    
	    System.out.println("Faux call to backend for ["  + cand + "]");
	    
    }
  }

}
 